<template>
  <div class="documents-explorer">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h3 class="page-title">
          <el-icon><Folder /></el-icon>
          文档管理
        </h3>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>全部文档</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      
      <div class="toolbar-right">
        <el-input
          v-model="searchQuery"
          placeholder="搜索文档..."
          clearable
          style="width: 300px"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-segmented v-model="viewMode" :options="viewOptions" size="default">
          <template #default="{ item }">
            <div style="padding: 4px">
              <el-icon :size="18">
                <component :is="item.icon" />
              </el-icon>
            </div>
          </template>
        </el-segmented>
        
        <el-button v-if="userStore.isAdmin" type="primary" @click="showUploadDialog">
          <el-icon><Upload /></el-icon>
          上传文档
        </el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-bar">
      <div class="stat-item">
        <el-icon><Document /></el-icon>
        <span>{{ filteredDocuments.length }} 个文档</span>
      </div>
      <div class="stat-item">
        <el-icon><Coin /></el-icon>
        <span>总大小: {{ totalSize }}</span>
      </div>
    </div>

    <!-- 文档网格视图 -->
    <div v-if="viewMode === 'grid'" class="grid-view" v-loading="loading">
      <div v-if="filteredDocuments.length === 0" class="empty-state">
        <el-empty description="暂无文档">
          <el-button v-if="userStore.isAdmin" type="primary" @click="showUploadDialog">
            上传第一个文档
          </el-button>
        </el-empty>
      </div>
      
      <div v-else class="documents-grid">
        <div
          v-for="doc in paginatedDocuments"
          :key="doc.id"
          class="document-card"
          @click="handleView(doc)"
          @contextmenu.prevent="handleContextMenu($event, doc)"
        >
          <div class="card-icon">
            <el-icon :size="48" :color="getFileIconColor(doc.file_type)">
              <component :is="getFileIcon(doc.file_type)" />
            </el-icon>
          </div>
          <div class="card-info">
            <div class="card-title" :title="doc.title">{{ doc.title }}</div>
            <div class="card-filename" :title="doc.filename">{{ doc.filename }}</div>
            <div class="card-meta">
              <el-tag size="small" :type="getFileTypeTag(doc.file_type)">
                {{ doc.file_type.toUpperCase() }}
              </el-tag>
              <span class="file-size">{{ formatFileSize(doc.file_size) }}</span>
            </div>
            <div class="card-footer">
              <span class="upload-user">
                <el-icon><User /></el-icon>
                {{ doc.upload_user }}
              </span>
              <span class="upload-time">{{ formatTime(doc.created_at) }}</span>
            </div>
          </div>
          
          <div v-if="userStore.isAdmin" class="card-actions">
            <el-button
              size="small"
              circle
              @click.stop="handleDelete(doc)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 文档列表视图 -->
    <div v-else class="list-view" v-loading="loading">
      <el-table
        :data="paginatedDocuments"
        stripe
        @row-click="handleView"
        style="width: 100%"
      >
        <el-table-column width="60">
          <template #default="{ row }">
            <el-icon :size="32" :color="getFileIconColor(row.file_type)">
              <component :is="getFileIcon(row.file_type)" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="filename" label="文件名" min-width="150" show-overflow-tooltip />
        <el-table-column prop="file_type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag size="small" :type="getFileTypeTag(row.file_type)">
              {{ row.file_type.toUpperCase() }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="file_size" label="大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.file_size) }}
          </template>
        </el-table-column>
        <el-table-column prop="upload_user" label="上传者" width="120" />
        <el-table-column prop="created_at" label="上传时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column v-if="userStore.isAdmin" label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              link
              @click.stop="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div v-if="filteredDocuments.length > pageSize" class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="filteredDocuments.length"
        layout="prev, pager, next, jumper, total"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文档"
      width="500px"
    >
      <el-form
        ref="uploadFormRef"
        :model="uploadForm"
        label-width="100px"
      >
        <el-form-item label="文档标题">
          <el-input
            v-model="uploadForm.title"
            placeholder="选填，留空则使用文件名"
          />
        </el-form-item>

        <el-form-item label="选择文件">
          <el-upload
            ref="uploadRef"
            drag
            :auto-upload="false"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            accept=".txt,.md,.docx,.doc,.pdf,.csv,.xlsx,.xls"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到这里或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 txt, md, docx, doc, pdf, csv, xlsx, xls 格式，最大 16MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUpload" :loading="uploading">
          上传
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看文档对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="文档详情"
      width="900px"
      top="5vh"
    >
      <div v-if="currentDocument">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="标题" :span="2">
            {{ currentDocument.title }}
          </el-descriptions-item>
          <el-descriptions-item label="文件名">
            {{ currentDocument.filename }}
          </el-descriptions-item>
          <el-descriptions-item label="文件类型">
            <el-tag :type="getFileTypeTag(currentDocument.file_type)">
              {{ currentDocument.file_type.toUpperCase() }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="文件大小">
            {{ formatFileSize(currentDocument.file_size) }}
          </el-descriptions-item>
          <el-descriptions-item label="上传者">
            {{ currentDocument.upload_user }}
          </el-descriptions-item>
          <el-descriptions-item label="上传时间" :span="2">
            {{ formatTime(currentDocument.created_at) }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider />

        <div class="document-content-header">
          <h4>文档内容</h4>
          <el-button size="small" @click="copyContent">
            <el-icon><CopyDocument /></el-icon>
            复制内容
          </el-button>
        </div>
        <div class="document-content">
          {{ documentContent }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Folder, Search, Upload, Document, Coin, User, Delete,
  Grid, List, UploadFilled, CopyDocument, 
  Document as DocumentIcon, Tickets, Reading, Picture
} from '@element-plus/icons-vue'
import api from '../api'
import { useUserStore } from '../store'

const userStore = useUserStore()

// 视图模式
const viewMode = ref('grid')
const viewOptions = [
  { label: 'grid', value: 'grid', icon: Grid },
  { label: 'list', value: 'list', icon: List }
]

// 数据
const documents = ref([])
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(20)

// 上传对话框
const uploadDialogVisible = ref(false)
const uploadFormRef = ref(null)
const uploadRef = ref(null)
const uploading = ref(false)
const uploadForm = ref({
  title: '',
  file: null
})

// 查看对话框
const viewDialogVisible = ref(false)
const currentDocument = ref(null)
const documentContent = ref('')

// 计算属性
const filteredDocuments = computed(() => {
  if (!searchQuery.value) {
    return documents.value
  }
  
  const query = searchQuery.value.toLowerCase()
  return documents.value.filter(
    doc =>
      doc.title.toLowerCase().includes(query) ||
      doc.filename.toLowerCase().includes(query)
  )
})

const paginatedDocuments = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredDocuments.value.slice(start, end)
})

const totalSize = computed(() => {
  const total = documents.value.reduce((sum, doc) => sum + (doc.file_size || 0), 0)
  return formatFileSize(total)
})

// 方法
const loadDocuments = async () => {
  loading.value = true
  try {
    const response = await api.get('/documents')
    if (response.success) {
      documents.value = response.documents
    }
  } catch (error) {
    console.error('加载文档列表失败:', error)
    ElMessage.error('加载文档列表失败')
  } finally {
    loading.value = false
  }
}

const showUploadDialog = () => {
  uploadForm.value = {
    title: '',
    file: null
  }
  uploadDialogVisible.value = true
}

const handleFileChange = (file) => {
  uploadForm.value.file = file.raw
}

const handleFileRemove = () => {
  uploadForm.value.file = null
}

const handleUpload = async () => {
  if (!uploadForm.value.file) {
    ElMessage.warning('请选择要上传的文件')
    return
  }

  uploading.value = true

  try {
    const formData = new FormData()
    formData.append('file', uploadForm.value.file)
    if (uploadForm.value.title) {
      formData.append('title', uploadForm.value.title)
    }

    const response = await api.upload('/documents/upload', formData)

    if (response.success) {
      ElMessage.success('文档上传成功')
      uploadDialogVisible.value = false
      loadDocuments()
    } else {
      ElMessage.error(response.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败：' + (error.response?.message || error.message))
  } finally {
    uploading.value = false
  }
}

const handleView = async (row) => {
  try {
    const response = await api.get(`/documents/${row.id}`)
    if (response.success) {
      currentDocument.value = response.document
      documentContent.value = response.content || '暂无内容'
      viewDialogVisible.value = true
    } else {
      ElMessage.error('获取文档详情失败')
    }
  } catch (error) {
    console.error('获取文档详情失败:', error)
    ElMessage.error('获取文档详情失败')
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文档"${row.title}"吗？物理文件也将被删除，此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    const response = await api.delete(`/documents/${row.id}`)
    if (response.success) {
      ElMessage.success(response.message || '文档已删除')
      loadDocuments()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleContextMenu = (event, doc) => {
  // 可以在这里添加右键菜单功能
  console.log('Right click:', doc)
}

const handleSearch = () => {
  currentPage.value = 1
}

const handlePageChange = () => {
  // 页码变化时自动更新
}

const copyContent = () => {
  navigator.clipboard.writeText(documentContent.value)
  ElMessage.success('内容已复制到剪贴板')
}

const getFileIcon = (type) => {
  const iconMap = {
    'txt': DocumentIcon,
    'md': Reading,
    'docx': Tickets,
    'doc': Tickets,
    'pdf': Reading,
    'csv': Tickets,
    'xlsx': Tickets,
    'xls': Tickets
  }
  return iconMap[type] || DocumentIcon
}

const getFileIconColor = (type) => {
  const colorMap = {
    'txt': '#909399',
    'md': '#67C23A',
    'docx': '#409EFF',
    'doc': '#409EFF',
    'pdf': '#F56C6C',
    'csv': '#E6A23C',
    'xlsx': '#67C23A',
    'xls': '#67C23A'
  }
  return colorMap[type] || '#909399'
}

const getFileTypeTag = (type) => {
  const typeMap = {
    'txt': '',
    'md': 'success',
    'docx': 'primary',
    'doc': 'primary',
    'pdf': 'danger',
    'csv': 'warning',
    'xlsx': 'success',
    'xls': 'success'
  }
  return typeMap[type] || 'info'
}

const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

const formatTime = (time) => {
  return new Date(time).toLocaleString('zh-CN')
}

onMounted(() => {
  loadDocuments()
})
</script>

<style scoped>
.documents-explorer {
  padding: 0;
  width: 100%;
  height: calc(100vh - var(--header-height) - 48px);
  display: flex;
  flex-direction: column;
  background: var(--bg-secondary);
}

/* 工具栏 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-xl) var(--spacing-2xl);
  background: var(--bg-primary);
  border-bottom: 1px solid var(--border-lighter);
  box-shadow: var(--shadow-xs);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: var(--spacing-xl);
}

.page-title {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  margin: 0;
  font-family: var(--font-family);
  font-size: var(--font-size-xl);
  font-weight: 500;
  color: var(--text-primary);
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
}

/* 统计栏 */
.stats-bar {
  display: flex;
  align-items: center;
  gap: var(--spacing-2xl);
  padding: var(--spacing-md) var(--spacing-2xl);
  background: var(--bg-primary);
  border-bottom: 1px solid var(--border-lighter);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

/* 网格视图 */
.grid-view {
  flex: 1;
  overflow-y: auto;
  padding: var(--spacing-2xl);
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.documents-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: var(--spacing-lg);
}

.document-card {
  position: relative;
  background: var(--bg-primary);
  border: 1px solid var(--border-lighter);
  border-radius: var(--radius-lg);
  padding: var(--spacing-xl);
  cursor: pointer;
  transition: all 0.2s ease;
  overflow: hidden;
}

.document-card:hover {
  border-color: var(--primary-blue);
  box-shadow: var(--shadow-md);
  transform: translateY(-2px);
}

.card-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
  margin-bottom: var(--spacing-lg);
}

.card-info {
  text-align: center;
}

.card-title {
  font-weight: 500;
  font-size: var(--font-size-md);
  color: var(--text-primary);
  margin-bottom: var(--spacing-sm);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-filename {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
  margin-bottom: var(--spacing-md);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-meta {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-md);
}

.file-size {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
}

.card-footer {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
  padding-top: var(--spacing-md);
  border-top: 1px solid var(--border-lighter);
}

.upload-user {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.upload-time {
  text-align: center;
}

.card-actions {
  position: absolute;
  top: var(--spacing-sm);
  right: var(--spacing-sm);
  opacity: 0;
  transition: opacity 0.2s ease;
}

.document-card:hover .card-actions {
  opacity: 1;
}

/* 列表视图 */
.list-view {
  flex: 1;
  overflow-y: auto;
  padding: var(--spacing-2xl);
}

:deep(.el-table) {
  background: var(--bg-primary);
  border-radius: var(--radius-lg);
  overflow: hidden;
}

:deep(.el-table__row) {
  cursor: pointer;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  padding: var(--spacing-xl);
  background: var(--bg-primary);
  border-top: 1px solid var(--border-lighter);
}

/* 文档内容显示 */
.document-content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-md);
}

.document-content-header h4 {
  margin: 0;
  font-family: var(--font-family);
  font-weight: 500;
}

.document-content {
  background: #f5f5f5;
  padding: var(--spacing-xl);
  border-radius: var(--radius-md);
  max-height: 500px;
  overflow: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.6;
}

/* 滚动条 */
.grid-view::-webkit-scrollbar,
.list-view::-webkit-scrollbar,
.document-content::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.grid-view::-webkit-scrollbar-track,
.list-view::-webkit-scrollbar-track,
.document-content::-webkit-scrollbar-track {
  background: transparent;
}

.grid-view::-webkit-scrollbar-thumb,
.list-view::-webkit-scrollbar-thumb,
.document-content::-webkit-scrollbar-thumb {
  background: var(--border-light);
  border-radius: var(--radius-full);
}

/* 响应式 */
@media (max-width: 768px) {
  .documents-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
  }
  
  .toolbar {
    flex-direction: column;
    gap: var(--spacing-md);
    align-items: stretch;
  }
  
  .toolbar-right {
    flex-direction: column;
    gap: var(--spacing-md);
  }
}
</style>

